/**
 * Excel文件读取工具
 * 用于将house_owner.xls转换为JSON格式，以便进行数据融合
 */

// 引入xlsx库来处理Excel文件
// 注意：需要先安装 npm install xlsx

class ExcelDataProcessor {
    constructor() {
        this.propertyData = []
        this.spatialData = []
    }

    /**
     * 读取Excel文件并转换为JSON
     * 由于浏览器安全限制，这个功能需要用户上传文件
     */
    async processExcelFile(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader()

            reader.onload = e => {
                try {
                    // 使用xlsx库解析Excel文件
                    const data = new Uint8Array(e.target.result)
                    const workbook = XLSX.read(data, { type: 'array' })

                    // 获取第一个工作表
                    const sheetName = workbook.SheetNames[0]
                    const worksheet = workbook.Sheets[sheetName]

                    // 转换为JSON
                    const jsonData = XLSX.utils.sheet_to_json(worksheet)

                    // 标准化权属数据
                    this.propertyData = this.standardizePropertyData(jsonData)

                    console.log(
                        `✅ Excel文件解析完成，共${this.propertyData.length}条权属记录`
                    )
                    resolve(this.propertyData)
                } catch (error) {
                    console.error('❌ Excel文件解析失败:', error)
                    reject(error)
                }
            }

            reader.onerror = () => reject(new Error('文件读取失败'))
            reader.readAsArrayBuffer(file)
        })
    }

    /**
     * 标准化权属数据格式
     * 将Excel中的数据转换为统一的JSON格式
     */
    standardizePropertyData(rawData) {
        return rawData
            .map((record, index) => {
                // 根据Excel文件的实际列名进行映射
                // 这里需要根据实际的Excel文件结构调整字段名
                return {
                    id: `property_${index}`,

                    // 房屋基本信息
                    buildingNumber:
                        record['楼栋'] ||
                        record['建筑编号'] ||
                        record['building_no'],
                    unitNumber:
                        record['单元'] || record['单元号'] || record['unit_no'],
                    floorNumber:
                        record['楼层'] || record['层数'] || record['floor_no'],
                    roomNumber:
                        record['房号'] || record['房间号'] || record['room_no'],

                    // 完整房屋编号（用于匹配）
                    fullRoomId: this.generateFullRoomId(record),

                    // 地址信息
                    address:
                        record['地址'] ||
                        record['详细地址'] ||
                        record['address'],
                    district: record['区域'] || record['district'],
                    community:
                        record['小区'] || record['社区'] || record['community'],

                    // 权属信息
                    ownerInfo: {
                        name:
                            record['业主姓名'] ||
                            record['产权人'] ||
                            record['owner_name'],
                        idCard:
                            record['身份证号'] ||
                            record['证件号'] ||
                            record['id_card'],
                        phone:
                            record['联系电话'] ||
                            record['手机号'] ||
                            record['phone'],
                        certificateNumber:
                            record['产权证号'] || record['证书编号'],
                    },

                    // 房屋属性
                    propertyInfo: {
                        area: this.parseNumber(
                            record['建筑面积'] ||
                                record['面积'] ||
                                record['area']
                        ),
                        usableArea: this.parseNumber(
                            record['使用面积'] || record['实用面积']
                        ),
                        propertyType:
                            record['房屋用途'] ||
                            record['用途'] ||
                            record['property_type'],
                        propertyNature:
                            record['产权性质'] || record['房屋性质'],
                        condition:
                            record['房屋状态'] ||
                            record['状态'] ||
                            record['condition'],
                        completionDate:
                            record['竣工时间'] || record['建成时间'],
                        registrationDate:
                            record['登记时间'] || record['办证时间'],
                    },

                    // 坐标信息（如果有）
                    coordinates: this.extractCoordinates(record),

                    // 原始数据保留
                    originalData: record,
                }
            })
            .filter(item => item.buildingNumber && item.roomNumber) // 过滤无效记录
    }

    /**
     * 生成完整的房屋编号，用于与空间数据匹配
     */
    generateFullRoomId(record) {
        const community = record['小区'] || record['社区'] || '安滨嘉苑'
        const building = record['楼栋'] || record['建筑编号']
        const room = record['房号'] || record['房间号']

        if (building && room) {
            return `${community}-${building}-${room}`
        }
        return null
    }

    /**
     * 解析数值字段
     */
    parseNumber(value) {
        if (typeof value === 'number') return value
        if (typeof value === 'string') {
            // 移除非数字字符，保留小数点
            const cleaned = value.replace(/[^\d.]/g, '')
            const parsed = parseFloat(cleaned)
            return isNaN(parsed) ? null : parsed
        }
        return null
    }

    /**
     * 提取坐标信息
     */
    extractCoordinates(record) {
        const lng = this.parseNumber(
            record['经度'] || record['longitude'] || record['lng']
        )
        const lat = this.parseNumber(
            record['纬度'] || record['latitude'] || record['lat']
        )

        if (lng && lat) {
            return { longitude: lng, latitude: lat }
        }
        return null
    }

    /**
     * 处理common.js中的空间数据
     */
    processSpatialData(commonJsData) {
        // 处理BIM模型数据
        const bimData = commonJsData.queryBimData().map(item => ({
            type: 'building',
            buildingId: item.d,
            title: item.title,
            position: {
                longitude: item.lng,
                latitude: item.lat,
            },
            height: item.height,
            modelUrl: item.url,
            originalData: item,
        }))

        // 处理房屋单元数据
        const buildingData = commonJsData.queryBuildingData().map(item => ({
            type: 'unit',
            fullRoomId: item.id, // 这个字段用于匹配
            position: {
                longitude: item.lng,
                latitude: item.lat,
                elevation: item.heigh,
            },
            dimensions: {
                length: item.length,
                width: item.width,
                height: item.height,
            },
            baseHeight: item.baseHeight,
            rotation: item.mz,

            // 解析房屋编号
            parsedInfo: this.parseRoomId(item.id),

            originalData: item,
        }))

        this.spatialData = [...bimData, ...buildingData]
        return this.spatialData
    }

    /**
     * 解析房屋编号
     * 从"安滨嘉苑-D1-106"中提取小区、楼栋、房号信息
     */
    parseRoomId(fullId) {
        const parts = fullId.split('-')
        if (parts.length >= 3) {
            return {
                community: parts[0],
                building: parts[1],
                room: parts[2],
            }
        }
        return null
    }

    /**
     * 生成模拟权属数据（用于演示）
     * 基于空间数据生成对应的权属信息
     */
    generateMockPropertyData() {
        const mockOwners = [
            '张三',
            '李四',
            '王五',
            '赵六',
            '钱七',
            '孙八',
            '周九',
            '吴十',
            '郑十一',
            '王十二',
            '李十三',
            '张十四',
            '陈十五',
            '杨十六',
        ]

        const conditions = ['已售', '待售', '抵押', '查封', '租赁']
        const propertyTypes = ['住宅', '商业', '办公', '储藏']

        // 基于spatial data生成权属数据
        const units = this.spatialData.filter(item => item.type === 'unit')
        this.propertyData = units.map((unit, index) => {
            const parsedInfo = unit.parsedInfo
            const ownerIndex = index % mockOwners.length
            const conditionIndex = index % conditions.length
            const typeIndex = index % propertyTypes.length
            return {
                id: `property_${index}-我是随机生成的权熟数据`,

                buildingNumber: parsedInfo?.building || 'D1',
                unitNumber:
                    Math.floor(parseInt(parsedInfo?.room || '101') / 100) || 1,
                floorNumber: parsedInfo?.room.toString().slice(0, -2) * 1,
                // Math.floor(
                //     (parseInt(parsedInfo?.room || '101') % 100) / 10
                // ) || 1,
                roomNumber: parsedInfo?.room || '101',
                fullRoomId: unit.fullRoomId + 'sss',

                address: `${parsedInfo?.community || '安滨嘉苑'}${
                    parsedInfo?.building || 'D1'
                }栋${parsedInfo?.room || '101'}室`,
                community: parsedInfo?.community || '安滨嘉苑',

                ownerInfo: {
                    name: mockOwners[ownerIndex],
                    idCard: `32012319900101${(1000 + index)
                        .toString()
                        .slice(-4)}`,
                    phone: `138123456${(10 + (index % 90))
                        .toString()
                        .slice(-2)}`,
                },

                propertyInfo: {
                    area: 80 + Math.random() * 40, // 80-120平米
                    propertyType: propertyTypes[typeIndex],
                    condition: conditions[conditionIndex],
                },

                coordinates: {
                    longitude:
                        unit.position.longitude +
                        (Math.random() - 0.5) * 0.0001,
                    latitude:
                        unit.position.latitude + (Math.random() - 0.5) * 0.0001,
                },
            }
        })

        this.propertyData = [
            {
                id: 'property_0-我是随机生成的权熟数据',
                buildingNumber: 'D1',
                unitNumber: 1,
                floorNumber: 1,
                roomNumber: '107',
                fullRoomId: '安滨嘉苑-D1-107',
                address: '安滨嘉苑D1栋107室',
                community: '安滨嘉苑',
                ownerInfo: {
                    name: '张三',
                    idCard: '320123199001011000',
                    phone: '13812345610',
                },
                propertyInfo: {
                    area: 95.26646115575144,
                    propertyType: '住宅',
                    condition: '已售',
                },
                coordinates: {
                    longitude: 120.62139919546817,
                    latitude: 30.16128712839312,
                },
            },
            {
                id: 'property_1-我是随机生成的权熟数据',
                buildingNumber: 'D1',
                unitNumber: 2,
                floorNumber: 2,
                roomNumber: '306',
                fullRoomId: '安滨嘉苑-D1-306',
                address: '安滨嘉苑D1栋306室',
                community: '安滨嘉苑',
                ownerInfo: {
                    name: '李四',
                    idCard: '320123199001011001',
                    phone: '13812345611',
                },
                propertyInfo: {
                    area: 116.65659154474933,
                    propertyType: '商业',
                    condition: '待售',
                },
                coordinates: {
                    longitude: 120.62138434769074,
                    latitude: 30.161340249147447,
                },
            },
        ]

        console.log('模拟数据权熟数据', this.propertyData)

        return this.propertyData
    }

    /**
     * 导出处理后的数据
     */
    exportProcessedData() {
        return {
            spatialData: this.spatialData,
            propertyData: this.propertyData,
            statistics: {
                spatialRecords: this.spatialData.length,
                propertyRecords: this.propertyData.length,
                buildingCount: this.spatialData.filter(
                    item => item.type === 'building'
                ).length,
                unitCount: this.spatialData.filter(item => item.type === 'unit')
                    .length,
            },
        }
    }
}
